"use strict";
import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store";
import { routes, asyncRoutes } from "./routes";
Vue.use(VueRouter);

// 修复 Error: Avoided redundant navigation to current location
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch((err) => err);
};
const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function (location) {
  return originalReplace.call(this, location).catch((err) => err);
};

/**
 * 根据用户角色动态生成路由
 * 返回 roles不存在 | roles包含账户角色的路由
 * @param {*} role 用户角色
 * @returns
 */
function generateAsyncRoutes(role = store.getters.role) {
  let roters = asyncRoutes.filter(
    (node) => !node.meta?.roles || node.meta?.roles.includes(role)
  );
  return routes.concat(roters);
}

const router = new VueRouter({
  base: process.env.BASE_URL,
  routes: generateAsyncRoutes()
});

/**
 * 根据角色信息初始化路由
 * 登录后调用
 * @param {*} role
 */
export function initialRouter(role) {
  router.matcher = new VueRouter({
    routes: generateAsyncRoutes(role)
  }).matcher;
}

export default router;
